# -*- coding: UTF-8 -*- 
import os, stat, datetime, time
import requests, json


def sendDataToAWIT(data):
    url = 'http://meteo.awit.net.cn:10280/GuiYang_weather_BS/push.do?pushData&username=demo&password=demo123'
    # s = json.dumps({'key1': 'value1', 'key2': 'value2'})
    r = requests.post(url, data=data)
    with open(filename, 'ab') as file:
        file.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ':' + r.text + '\n')


def getForecastData(name, lat, lng, end):
    data_url = 'http://114.32.127.222/tea/API/FCST/fcst_value_api.php?lon=' + lng + '&lat=' + lat + '&end=' + end

    html = requests.get(data_url)
    if html.status_code == 200:
        res = html.content
        finalData = res[:1] + '{lat:' + lat + ',lng:' + lng + '},' + res[1:]
        sendDataToAWIT(finalData)
        with open(filename, 'ab') as file:
            file.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ':Getting Data For ' + name + '(' + str(
                len(finalData)) + ')' + '\n')


def getStationList():
    data_url = 'http://meteo.awit.net.cn:10280/GuiYang_weather_BS/weatherData.do?getActivedForcast'

    html = requests.get(data_url)
    if html.status_code == 200:
        stations_json = json.loads(html.content)
        return stations_json['obj']['data']


def main():
    try:
        # 是否有这个路径
        if not os.path.exists(log_path):
            # 创建路径
            os.makedirs(log_path)
        # 拼接图片名（包含路径）
    except IOError:
        print("IOError")
    except Exception:
        print("Exception")
    stations = getStationList()
    for i in range(len(stations)):
        forecasttime = (datetime.datetime.now() + datetime.timedelta(hours=38)).strftime("%Y%m%d%H")
        getForecastData(stations[i]['num'], str(stations[i]['lat']), str(stations[i]['lng']), forecasttime)


log_path = '/Users/fantasy/Downloads'
log_name = 'meteo_getForecastData.txt'
filename = os.path.join(log_path, log_name)
if __name__ == "__main__":
    main()
